package com.gao.controller.config;

import com.gao.pojo.User;
import com.gao.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Projectname springboot-08-shiro
 * @Filename UserRealm
 * @Author an
 * @Data 2022/8/14 19:00
 * @Description TODO
 */

//自定义的UserRealm
public class UserRealm  extends AuthorizingRealm {


    @Autowired
    UserService userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权=>doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");

        //拿到当前用户登录的的对象
        Subject subject = SecurityUtils.getSubject();
        User currentuser = (User) subject.getPrincipal();//拿到user对象
        //设置当前用户的权限
        info.addStringPermission(currentuser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证=>doGetAuthenticationInfo");

//        String name = "root";
//        String password = "123456";
        UsernamePasswordToken userToken =  (UsernamePasswordToken) authenticationToken;
        //链接真实数据库
        User user = userService.queryUserByName(userToken.getUsername());

        if (user == null){//没有用户
            return null;
        }

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);


//        if (!userToken.getUsername().equals(name)){
//            return null;  //抛出异常   UnknownAccountException
//        }

        //可以加密 MD5 MD5盐值加密
        //密码认证，shiro做
//        return new SimpleAuthenticationInfo("",password,"");
//        return new SimpleAuthenticationInfo("",user.getPassword(),"");
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");//可以把user传递给授权
    }
}
